package com.css.upms.biz.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.css.common.core.constent.CommonConstant;
import com.css.upms.api.entity.SysRole;
import com.css.upms.api.entity.SysRoleDept;
import com.css.upms.biz.mapper.SysRoleDeptMapper;
import com.css.upms.biz.service.SysRoleDeptService;
import com.css.upms.biz.service.SysRoleService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 角色机构关系
 *
 * @author hanyx
 * @date 2019-05-03 02:50:41
 */
@Service("sysRoleDeptService")
@AllArgsConstructor
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDeptMapper, SysRoleDept> implements SysRoleDeptService {

    private final SysRoleService sysRoleService;

    /**
     * 角色机构关系简单分页查询
     *
     * @param sysRoleDept 角色机构关系
     * @return
     */
    @Override
    public IPage<SysRoleDept> getSysRoleDeptPage(Page<SysRoleDept> page, SysRoleDept sysRoleDept) {
        return baseMapper.getSysRoleDeptPage(page, sysRoleDept);
    }

    /**
     * 角色-数据权限设置
     * @param roleId
     * @param deptIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveRoleDepts(String roleId, String deptIds) {
        if (StringUtils.isBlank(roleId)) {
            return Boolean.FALSE;
        }
        this.remove(Wrappers.<SysRoleDept>query().lambda()
                .eq(SysRoleDept::getRoleId, roleId));

        SysRole sysRole = sysRoleService.getById(roleId);
        if (StringUtils.isBlank(deptIds)) {
            sysRole.setDataScope(CommonConstant.DATA_SCOPE_ALL);
            sysRoleService.updateById(sysRole);
            return Boolean.TRUE;
        } else {
            sysRole.setDataScope(CommonConstant.DATA_SCOPE_CUSTOM);
            sysRoleService.updateById(sysRole);
        }

        List<SysRoleDept> roleDeptList = Arrays
                .stream(deptIds.split(","))
                .map(deptId -> {
                    SysRoleDept roleDept = new SysRoleDept();
                    roleDept.setRoleId(roleId);
                    roleDept.setDeptId(String.valueOf(deptId));
                    return roleDept;
                }).collect(Collectors.toList());

        return this.saveBatch(roleDeptList);
    }

}
